package algorithm_demo.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * 46. 全排列
 * <a href="https://leetcode.cn/problems/permutations/">https://leetcode.cn/problems/permutations/</a>
 * @author Api
 * @date 2023/5/5 1:14
 */
public class Problem_046_Permutations {
    List<List<Integer>> list2 = new ArrayList<>();
    public List<List<Integer>> permute(int[] nums) {
        if(nums.length == 0){
            return list2;
        }
        List<Integer> path = new ArrayList<>();
        boolean[] used = new boolean[nums.length];
        dfs(nums, path, used);
        return list2;
    }


    public void dfs(int[] nums, List<Integer> path, boolean[] used){
        if(path.size() == nums.length){
            list2.add(new ArrayList<Integer>(path));
            return;
        }
        for(int i = 0; i< nums.length; i++){
            //剪枝1，如果已经存在则跳过
            if(used[i] == true){
                continue;
            }
            used[i] = true;
            path.add(nums[i]);
            dfs(nums, path, used);
            //回溯
            path.remove(path.size()-1);
            used[i] = false;
        }
    }
}
